package cn.taobaoke.restful.controller;

import cn.taobaoke.restful.domain.DocumentEntity;
import cn.taobaoke.restful.interceptor.Auth;
import cn.taobaoke.restful.service.DocumentService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;


/**
 * @author yangzuo
 * @since 2017-04-18 22:01
 */
@RequestMapping("/{domain}/{domainId}/api/documents")
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class DocumentController extends BaseController {

    @Auth(type = Auth.AuthType.ADMIN)
    @PostMapping("")
    public Result saveDocument(@PathVariable Long domainId, @RequestBody DocumentEntity entity) {
        logger.debug("添加文案操作: POST /{}/api/documents", domainId);

        DocumentEntity documentEntity = documentService.saveDocument(entity, domainId);
        return wrapObj(documentEntity);
    }

    @GetMapping("/{id}")
    public Result getDocument(@PathVariable Long domainId, @PathVariable Long id) {
        logger.debug("查询文案操作: GET /{}/api/documents/{}", domainId, id);

        DocumentEntity entity = documentService.getDocumentById(id, domainId);
        return wrapObj(entity);
    }

    @Auth(type = Auth.AuthType.ADMIN)
    @DeleteMapping("/{id}")
    public Result deleteDocument(@PathVariable Long domainId, @PathVariable Long id) {
        logger.debug("删除文案操作: DELETE /{}/api/documents/{}", domainId, id);

        documentService.deleteDocumentById(id, domainId);
        return wrapVoid();
    }

    @Auth(type = Auth.AuthType.ADMIN)
    @PutMapping("/{id}")
    public Result updateDocument(@PathVariable Long domainId, @PathVariable Long id, @RequestBody DocumentEntity entity) {
        logger.debug("更新文案操作: PUT /{}/api/documents/{}", domainId, id);

        DocumentEntity documentEntity = documentService.updateDocument(id, entity, domainId);
        return wrapObj(documentEntity);
    }

    @GetMapping("")
    public Result pagingQueryDocuments(@PathVariable Long domainId, Integer size, Integer page) {
        logger.debug("分页查询文案列表: GET /{}/api/documents?size={}&page={}", domainId, size, page);

        Pageable pageable = createPageable(page, size);
        Page<DocumentEntity> pages = documentService.pagingQueryDocuments(pageable, domainId);
        return wrapObj(pages);
    }

    private final @NonNull
    DocumentService documentService;

    private static Logger logger = LogManager.getLogger(DocumentController.class);
}
